import socket
import sys, time
import threading


class udpSingleBoard(threading.Thread):
    def __init__(self, getPort, max_len) -> None:
        super().__init__()
        self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 获取本地主机名
        self.host = '127.0.0.1'
        # 设置端口号
        self.port = getPort
        self.msg = ""
        self.max_size = max_len

        try:
            self.udp.bind((self.host, self.port))
        except OSError:
            print("UDP bind 错误")

    def run(self):
        '''
        UDP收发
        '''
        while(True):
            time.sleep(0.2)
            self.msg = "UDP asssdjfsldfkald "
            try:
                self.udp.sendto(str.encode(self.msg, 'utf-8'),
                                (self.host, 10001))
            except OSError:
                print("OSError 发送失败")

            try:
                self.get_msg, self.addr = self.udp.recvfrom(1024)
                print("udp recv: " + str(self.get_msg, 'utf-8'))
            except OSError:
                print("UDP接收失败")
            except TypeError:
                print("type错误")
